package com.maigao.service;

import com.maigao.core.login.dto.WeixinLoginRecord;
import com.maigao.core.login.handler.LoginHandlerFactory;
import com.maigao.core.login.handler.WxThirdLoginHandler;
import com.maigao.entity.DomainConstant;
import com.maigao.entity.ThirdPartyCmd;
import com.maigao.entity.jpa.User;
import com.maigao.entity.vo.UserVO;
import com.maigao.persistent.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author awei
 * @description:
 * @date 2022/5/19 9:58 下午
 */
@Service
public class LoginService {

    @Autowired
    private LoginHandlerFactory loginHandlerFactory;

    @Autowired
    private UserService userService;

    @Autowired
    private IdentifyService identifyService;
    @Autowired
    private UserRepository userRepository;

    /**
     * 三方登录
     *
     * @param cmd
     * @return
     */
    public Triple<Boolean, UserVO, String> thirdParty(ThirdPartyCmd cmd) {
        User user = null;
        if (DomainConstant.ThirdLogin.WX.equals(cmd.getAuthType())) {
            WxThirdLoginHandler handler = (WxThirdLoginHandler) loginHandlerFactory.getHandler(cmd.getAuthType());
            WeixinLoginRecord record = handler.search(cmd.getJsCode());
            if (StringUtils.isEmpty(record.getOpenId())) {
                return Triple.of(false, null, "微信授权登录code已失效!");
            }
            if (StringUtils.isNotBlank(cmd.getUid())) {
                user = userService.findUserByUid(cmd.getUid());
                if (null == user) {
                    return Triple.of(false, null, "当前uid不存在!");
                }
            } else {
                user = userService.findUserByWxOpenId(record.getOpenId());
                if (null == user) {
                    return Triple.of(false, null, "当前用户没有访问权限!");
                }
            }
            if (StringUtils.isBlank(user.getWxOpenId())) {
                user.setWxOpenId(record.getOpenId());
                userRepository.save(user);
            }
        }
        String accessKey = identifyService.saveLoginToken(user);
        UserVO userInfo = userService.queryUserDetailInfo(user.getId(), user.getUid());
        userInfo.setAccessKey(accessKey);
        return Triple.of(true, userInfo, "");
    }
}
